import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { login as loginApi, logout as logoutApi, getCurrentUser } from '@/api/auth'

interface UserInfo {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  is_admin: boolean
  status: number
  avatar?: string
  permissions?: string[]
}

interface LoginData {
  username: string
  password: string
  captchaId: string
  captcha: string
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string>(localStorage.getItem('portal-web-token') || '')
  const userInfo = ref<UserInfo | null>(JSON.parse(localStorage.getItem('userInfo') || 'null'))

  const isAuthenticated = computed(() => !!token.value)

  /**
   * 登录
   * @param loginData 登录数据
   * @returns 是否登录成功
   */
  const login = async (loginData: LoginData): Promise<boolean> => {
    try {
      const res = await loginApi(loginData)
      
      if (res.code === 200 && res.data) {
        // 保存token和用户信息
        token.value = res.data.token
        userInfo.value = {
          id: res.data.user.id,
          username: res.data.user.username,
          nickname: res.data.user.nickname,
          email: res.data.user.email,
          phone: res.data.user.phone,
          is_admin: res.data.user.is_admin,
          status: res.data.user.status,
          // 使用默认头像或用户头像
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        }
        
        localStorage.setItem('portal-web-token', res.data.token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(res.message || '登录失败')
        return false
      }
    } catch (error) {
      // 错误信息已在request拦截器中处理
      return false
    }
  }

  /**
   * 登出
   */
  const logout = async (): Promise<void> => {
    try {
      // 调用登出API
      if (token.value) {
        await logoutApi()
      }
    } catch (error) {
      // 即使API调用失败，也清除本地数据
      console.error('登出API调用失败:', error)
    } finally {
      // 清除本地存储
      token.value = ''
      userInfo.value = null
      localStorage.removeItem('portal-web-token')
      localStorage.removeItem('userInfo')
      ElMessage.success('已退出登录')
    }
  }

  /**
   * 获取当前用户信息
   * @returns 是否获取成功
   */
  const fetchCurrentUser = async (): Promise<boolean> => {
    try {
      const res = await getCurrentUser()
      
      if (res.code === 200 && res.data) {
        userInfo.value = {
          id: res.data.id,
          username: res.data.username,
          nickname: res.data.nickname,
          email: res.data.email,
          phone: res.data.phone,
          is_admin: res.data.is_admin,
          status: res.data.status,
          permissions: res.data.permissions || [],
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        }
        
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        return true
      } else {
        // 如果获取用户信息失败，可能是token过期，清除登录状态
        logout()
        return false
      }
    } catch (error) {
      // 错误信息已在request拦截器中处理
      // 如果是401错误，会自动跳转到登录页
      return false
    }
  }

  /**
   * 初始化：从localStorage恢复token和用户信息
   */
  const init = (): void => {
    const savedToken = localStorage.getItem('portal-web-token')
    const savedUserInfo = localStorage.getItem('userInfo')
    
    if (savedToken) {
      token.value = savedToken
    }
    
    if (savedUserInfo) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        userInfo.value = null
      }
    }
  }

  return {
    token,
    userInfo,
    isAuthenticated,
    login,
    logout,
    fetchCurrentUser,
    init
  }
})

